﻿using FarmSmartSleep.Common.Contexts;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace FarmSmartSleep.Common.Infrastructure
{
    public class BaseRepository<T> : IBaseRepository<T> where T : class, new()
    {
        private readonly EFDBContext db;

        public BaseRepository(EFDBContext db)
        {
            this.db = db;
        }

        public int Add(T entity)
        {
            db.Set<T>().Add(entity);
            return db.SaveChanges();
        }

        public IQueryable<T> GetAll()
        {
            var list = db.Set<T>().AsQueryable();
            return list;
        }
        public int Update(T entity)
        {
            db.Set<T>().Update(entity);
            return db.SaveChanges();
        }

        public T GetById(int id)
        {
           return db.Set<T>().Find(id);
        
        }
        /// <summary>
        /// 异步添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> AddAsync(T entity)
        {
            db.Set<T>().Add(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 异步更新
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        public async Task<int> UpdateAsync(T entity)
        {
            db.Set<T>().Update(entity);
            return await db.SaveChangesAsync();
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="entitys"></param>
        /// <returns></returns>
        public async Task<int> AddRange(List<T> entitys)
        {
            db.Set<T>().AddRange(entitys);
            return await db.SaveChangesAsync();
        }
        public int UpdateRange(List<T> entitys)
        {
            db.Set<T>().UpdateRange(entitys);
            return db.SaveChanges();
        }
    }
}
